package com.cmc.cloud.cmclink.doc.framework.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.fastjson.JSON;
import com.cmc.cloud.cmclink.doc.vo.manifestvo.manifestcntr.ManifestCntrImportVo;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * excel 导入监听器
 *
 * @author 陈正
 */
@Slf4j
public class ManifestCntrExcelListener extends AnalysisEventListener<ManifestCntrImportVo> {

    private static String BLNO = "BLNO";

    private static String BOOKING_VESSEL = "船名";

    private Boolean importTypeCn = true;

    public Boolean getImportTypeCn() {
        return importTypeCn;
    }

    /**
     * 解析异常调用
     *
     * @param exception
     * @param context
     * @throws Exception
     */
    @Override
    public void onException(Exception exception, AnalysisContext context) {
        log.error("解析失败，但是继续解析下一行:{}", exception.getMessage());
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            log.error("第{}行，第{}列解析异常，数据为:{}", excelDataConvertException.getRowIndex(),
                    excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData());
        }
    }

    /**
     * 解析表头
     *
     * @param headMap
     * @param context
     */
    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        log.info("解析表头:{}", JSON.toJSONString(headMap));
        // 判断中英文表格
        for (int index = 0; index < headMap.size(); index++) {
            ReadCellData<?> column = headMap.get(index);
            if (BLNO.equals(column.getStringValue())) {
                importTypeCn = false;
                break;
            }
            if (BOOKING_VESSEL.equals(column.getStringValue())) {
                importTypeCn = true;
                break;
            }
        }
    }

    /**
     * 解析每行数据调用
     *
     * @param data
     * @param context
     */
    @Override
    public void invoke(ManifestCntrImportVo data, AnalysisContext context) {
    }

    @Override
    public void extra(CellExtra extra, AnalysisContext context) {
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
    }
}